package io.kimmking.rpcfx.client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

import static io.netty.handler.codec.http.HttpMethod.GET;

public class HttpClientHandler extends ChannelInboundHandlerAdapter {

    private String path;
    private HttpMethod httpMethod;
    private final ResponseCallback responseCallback;
    private final ResponseHolder responseHolder;


    public HttpClientHandler(String path, final ResponseCallback responseCallback, final ResponseHolder responseHolder){
        this.path = path;
        this.httpMethod = HttpMethod.GET;
        this.responseCallback = responseCallback;
        this.responseHolder = responseHolder;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        URI uri = new URI(path);
        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, httpMethod, uri.toASCIIString());
        request.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        request.headers().add(HttpHeaderNames.CONTENT_LENGTH,request.content().readableBytes());
        ctx.writeAndFlush(request);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        if(msg instanceof FullHttpResponse){
            FullHttpResponse response = (FullHttpResponse)msg;
            ByteBuf buf = response.content();
            //
            String result = buf.toString(CharsetUtil.UTF_8);
            System.out.println("response -> "+result);
            responseCallback.setResponse(result, responseHolder);
        }
    }
}
